package com.auerdi.ui.order;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auerdi.R;
import com.auerdi.dialog.PayWayDialog;
import com.auerdi.ui.account.evemt.RefleshAddressEvemt;
import com.auerdi.ui.account.view.TestInutView;
import com.auerdi.ui.detail.address.ADDressShowFragMent;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.AddressLists;
import com.example.egghttp.retrofit.beans.banner.CCLResponce;
import com.example.egghttp.retrofit.beans.banner.CartPlaceOrderResponce;
import com.example.egghttp.retrofit.beans.banner.LogInfo;
import com.example.egghttp.retrofit.beans.banner.OrderData;
import com.example.egghttp.retrofit.beans.banner.PayWeixinResponce;
import com.example.egghttp.retrofit.beans.goods.Address;
import com.example.egghttp.retrofit.beans.goods.Product;
import com.example.egghttp.retrofit.params.CartConFirmPinListsRequest;
import com.example.egghttp.retrofit.params.CartPlaceOrder;
import com.example.egghttp.retrofit.params.OrderSn;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import net.sourceforge.simcpux.Constants;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import es.dmoral.toasty.Toasty;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by YoKeyword on 16/2/14.
 */
public class ADOrderFragment extends SwipeBackFragment {


    @BindView(R.id.title_left)
    RelativeLayout titleLeft;
    Unbinder unbinder;

    @BindView(R.id.sendOrder)
    TextView sendOrder;
    @BindView(R.id.testPAy)
    TextView testPAy;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.et_megssage)
    TestInutView etMegssage;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.voo_txt)
    TextView vooTxt;
    @BindView(R.id.sum_price)
    TextView sumPrice;
    @BindView(R.id.sku_price)
    TextView skuPrice;
    @BindView(R.id.address_d)
    TextView addressD;

    @BindView(R.id.addr_eddit)
    View addrEddit;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.addressName)
    TextView addressName;
    @BindView(R.id.addressPhone)
    TextView addressPhone;
    @BindView(R.id.total_money)
    TextView totalMoney;


    private String nowAddressId = "0";
    //    private String mBuyInfos;
    private OrderData testPAyt;
    public static PayWeixinResponce payWeixinResponce;
    private IWXAPI api;
    private LogInfo loginfor;
    //    private String mBuyType;
    private static Product mProduct;
    private CCLResponce cclResponce;

    public static ADOrderFragment newInstance(Product product) {

        mProduct = product;
        Bundle args = new Bundle();
        ADOrderFragment fragment = new ADOrderFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onResume() {
        super.onResume();

        L.d("hcia", "onResume:");


        requestAddress();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ad_fragment_order, container, false);

        L.d("hcia", "view:" + view);

        api = WXAPIFactory.createWXAPI(getActivity(), Constants.APP_ID);
        api.registerApp(Constants.APP_ID);
        unbinder = ButterKnife.bind(this, view);

        View tpview = attachToSwipeBack(view);
//        L.d("hcia", "mBuyInfos:" + mBuyInfos);
        etMegssage.getEditText().setTextColor(Color.parseColor("#000000"));
        etMegssage.getEditText().setHintTextColor(Color.parseColor("#000000"));


        return tpview;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        L.d("hcia", "mProduct.getGoods_id():" + mProduct.getGoods_id() + "mProduct.getGoods_id():" + mProduct.getId());


        addrEddit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EventBus.getDefault().post(ADDressShowFragMent.newInstance());

            }
        });

        //2拼团价购买，4拼团直购，5团长价
        RetrofitClient.getPDAClient().create(AdService.class).teamConfirmLists(new CartConFirmPinListsRequest(mProduct.getBuyMode(), "0", mProduct.getId(), mProduct.getGood_num(), mProduct.getGood_spec()))//购买方式：1商店价购买，2拼团价购买，3砍价底价购买
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<CCLResponce>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);
                        pop();

                    }

                    @Override
                    public void onNext(BOb<CCLResponce> cclResponceBOb) {

                        L.d("hcia", "cclResponceBOb:" + cclResponceBOb);


//                        if (!cclResponceBOb.getCode().equals("10000")) {
////                            pop();
//                        }

                        cclResponce = cclResponceBOb.getBody();
//                        L.d("hcia", "cclResponce:" + cclResponce);
//                        L.d("hcia", "cclResponce.getPrice_data():" + cclResponce.getPrice_data());

//                        本单合计：￥299.00
                        sumPrice.setText("本单合计: ￥" + cclResponce.getPrice_data().getTotal_amount());
                        totalMoney.setText("合计: ￥" + cclResponce.getPrice_data().getTotal_amount());
                        title.setText(cclResponce.getGoods_list().get(0).getGoods_name() + "X" + cclResponce.getGoods_total_num());

//                        合计：￥299.00
//                        L.d("hcia", "cclResponce.getGoods_total_num():" + cclResponce.getGoods_total_num());
                    }
                });


        sendOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // buy_mode 购买方式：1商店价，2拼团价，3砍价底价
                // activity_type : 活动类型：1拼团，2砍价

                L.d("hcia", "nowAddressId:" + nowAddressId);

                if (cclResponce.getBuy_mode() == null) {

                    Toasty.error(getActivity(), "你的地址可能没填").show();
                    return;
                }


                RetrofitClient.getPDAClient().create(AdService.class).cartPlaceOrder(
                        new CartPlaceOrder(
                                "1"
                                , mProduct.getId()
                                , "0"
                                , cclResponce.getBuy_mode()
                                , nowAddressId
                                , etMegssage.getText() + ""
                                , ""
                                , "-1"
                                , "-1"
                                , "-1"
                                , mProduct.getGood_num()
                                , cclResponce.getGoods_list().get(0).getItem_id()
                                , "-1"
                                , "-1"
                                , cclResponce.getPrice_data().getTotal_amount()
                                , cclResponce.getPrice_data().getOrder_amount()
                                ,"0"
                        )
                )
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BOb<CartPlaceOrderResponce>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(BOb<CartPlaceOrderResponce> cartPlaceOrderResponceBOb) {

                                testPAyt = cartPlaceOrderResponceBOb.getBody().getOrder_data();
                                L.d("hcia", "testPAyt.getOrder_sn():" + testPAyt.getOrder_sn());

                                PayWayDialog.newInstance(testPAyt.getOrder_sn(), new PayWayDialog.PayWayListener() {
                                    @Override
                                    public void onPayWay(Integer num) {
                                        PayReq payRequest = new PayReq();

                                        payRequest.appId = Constants.APP_ID;
                                        payRequest.partnerId = Constants.PARTER_ID;
                                        payRequest.prepayId = payWeixinResponce.getPrepay_id();
                                        payRequest.packageValue = "Sign=WXPay";
                                        payRequest.nonceStr = payWeixinResponce.getNonce_str();
                                        L.d("hcia", "payRequest.nonceStr:" + payRequest.nonceStr);
                                        payRequest.timeStamp = payWeixinResponce.getTimestamp();
                                        L.d("hcia", "payRequest.timeStamp:" + payRequest.timeStamp);
                                        payRequest.sign = payWeixinResponce.getSign();
                                        api.sendReq(payRequest);


                                        L.d("hcia", "payWeixinResponce.getOrder_sn():" + payWeixinResponce.getOrder_sn());
                                        L.d("hcia", "payWeixinResponce.getPrepay_id():" + payWeixinResponce.getPrepay_id());
                                        L.d("hcia", "payWeixinResponce.getSign():" + payWeixinResponce.getSign());
                                    }
                                }).show(getFragmentManager(), "");


//                                L.d("hcia", "testPAyt:" + testPAyt);


                                RetrofitClient.getPDAClient().create(AdService.class).payWeixin(new OrderSn(testPAyt.getOrder_sn()))
                                        .subscribeOn(Schedulers.newThread())
                                        .observeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Subscriber<BOb<PayWeixinResponce>>() {
                                            @Override
                                            public void onCompleted() {

                                            }

                                            @Override
                                            public void onError(Throwable e) {

                                            }

                                            @Override
                                            public void onNext(BOb<PayWeixinResponce> payWeixinResponceBOb) {

                                                payWeixinResponce = payWeixinResponceBOb.getBody();
//                                                L.d("hcia", "payWeixinResponce:" + payWeixinResponce);

                                            }
                                        });
                            }
                        });

            }
        });

        testPAy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                RandomStringUtils.randomAlphanumeric(5);
//                api.registerApp(Constants.APP_ID);


            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Address address) {

        addressName.setText(address.getConsignee());
        addressPhone.setText(address.getMobile());
        addressD.setText(address.getAddress());
        nowAddressId = address.getAddress_id();

        L.d("hcia", "event.getAddressId():" + address.getAddress_id());

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefleshAddressEvemt address) {

        L.d("hcia", "RefleshAddressEvemt:");

        requestAddress();

    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void requestAddress() {
        RetrofitClient.getPDAClient().create(AdService.class).addressLists()
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<AddressLists>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);


                    }

                    @Override
                    public void onNext(BOb<AddressLists> addressListsBOb) {
                        List<Address> addressList = addressListsBOb.getBody().getAddress_list();

//                        Collections.sort(addressList, (arg0, arg1) -> arg0.getIs_default().compareTo(arg1.getIs_default()));

//                        addressD.setText(addressList.get(0).getAddress());
//                        nowAddressId = addressList.get(0).getAddress_id();


                        if (addressList.size() == 0) {

                            addressName.setText("***");
                            addressPhone.setText("1***********");
                            addressD.setText("***********");
                            nowAddressId = "0";

                            return;
                        }

                        Address address = addressList.get(0);
                        addressName.setText(address.getConsignee());
                        addressPhone.setText(address.getMobile());
                        addressD.setText(address.getAddress());
                        nowAddressId = address.getAddress_id();
//                        L.d("hcia", " addressList.size():" + addressList.size());

                    }
                });
    }


}
